package com.hccl.SMSDetector;

import com.hccl.answeringSystem.HanLPBinaryAnalyzer;
import com.hccl.answeringSystem.MySimilarity;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.similarities.ClassicSimilarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.json.*;

import java.util.Iterator;

/**
 * Created by Zhao on 2016/03/25.
 */
public class SMSLoader {

    private Analyzer hanalyzer = new HanLPBinaryAnalyzer();
    final Directory directory = new RAMDirectory();

    public void indexing(String jsonStr){
        try {
            IndexWriterConfig config = new IndexWriterConfig(hanalyzer);
            config.setSimilarity(new ClassicSimilarity());
            IndexWriter iWriter = new IndexWriter(directory, config);

            SMSReader smsreader = new SMSFileReader();
            SMSEntity sms;
            int indexID=0;
            JSONObject json=new JSONObject(jsonStr);
            JSONObject dataObject = json.getJSONObject("data");
            Iterator it = dataObject.keys();
            while (it.hasNext()) {
                String name = (String) it.next();
                Object content = dataObject.get(name);
                if ((sms=smsreader.getNextSMS((String)name,(String)content))!=null){
                    if(sms.isExclude()) continue;
                    Document doc=new Document();
                    FieldType fieldType = new FieldType(TextField.TYPE_STORED);
                    fieldType.setStoreTermVectors(true);
                    doc.add(new Field("content",sms.getSmsContent(), fieldType));
                    doc.add(new IntField("id", indexID, IntField.TYPE_STORED));
                    indexID++;
                    iWriter.addDocument(doc);
                }
            }
            iWriter.close();
            //smsreader.close();
        }
        catch (Exception e) {e.printStackTrace();}
    }

    public Directory getDirectory() {
        return directory;
    }
}
